﻿using QD.SQLHelper;
using QD.Tools;
using QD_Clients.Code.DbContent;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace QD_Clients
{
    public partial class SysCfgStruUpgrade : BaseForm
    {
        private DateTime StartProcessDate = DateTime.Now;//开始处理时间
        public SysCfgStruUpgrade()
        {
            InitializeComponent();
            this.gridApp.InitGrid();
            this.gridResult.InitGrid();
        }

        private void SysCfgStruUpgrade_Load(object sender, EventArgs e)
        {
            //获取软件列表作为模板软件名称下拉和软件列表数据源
            QDDevPlat_V4 db = new QDDevPlat_V4();
            DataTable dtApp = db.Query("select * from QDDataBase");
            //添加选择框栏位
            DataColumn dcIsSelected = new DataColumn("IsSelected",typeof(bool));
            dcIsSelected.DefaultValue = false;
            dtApp.Columns.Add(dcIsSelected);
            //添加扩展软件名称栏位
            DataColumn dcQfNameExt = new DataColumn("QfNameExt", typeof(string));
            dcQfNameExt.Expression = "QfName + '(' + QfCode + ')'";
            dtApp.Columns.Add(dcQfNameExt);

            DataTable dtApp2 = dtApp.Copy();
            this.gridApp.DataSource = dtApp;
            this.cmbTemplateAppName.DataSource = dtApp2;
        }

        private void gridApp_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            //不是序号列和标题列时才执行
            if (e.RowIndex != -1 && e.ColumnIndex != -1)
            {
                //checkbox 勾上
                if ((bool)gridApp.Rows[e.RowIndex].Cells["gridApp_IsSelected"].EditedFormattedValue == true)
                {
                    //选中改为不选中
                    this.gridApp.Rows[e.RowIndex].Cells["gridApp_IsSelected"].Value = false;
                }
                else
                {
                    //不选中改为选中
                    this.gridApp.Rows[e.RowIndex].Cells["gridApp_IsSelected"].Value = true;
                }
            }
        }

        private void gridResult_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            //不是序号列和标题列时才执行
            if (e.RowIndex != -1 && e.ColumnIndex != -1)
            {
                //checkbox 勾上
                if ((bool)gridResult.Rows[e.RowIndex].Cells["gridResult_IsSelected"].EditedFormattedValue == true)
                {
                    //选中改为不选中
                    this.gridResult.Rows[e.RowIndex].Cells["gridResult_IsSelected"].Value = false;
                }
                else
                {
                    //不选中改为选中
                    this.gridResult.Rows[e.RowIndex].Cells["gridResult_IsSelected"].Value = true;
                }
            }
        }

        //获取表差异
        private void tsbGetDiff_Click(object sender, EventArgs e)
        {
            this.gridApp.EndEdit();
            this.Cursor = Cursors.WaitCursor;
            this.tsbGetDiff.Enabled = false;
            //检查参数
            string templateAppCode = string.Concat(this.cmbTemplateAppName.SelectedValue);
            int rowsCount = this.gridApp.Rows.Count;
            DataTable dtApp = (DataTable)this.gridApp.DataSource;
            dtApp.AcceptChanges();
            string upgradeAppCode = string.Join(",", dtApp.AsEnumerable().Where(t => t.Field<bool>("IsSelected")).Select(t => t.Field<string>("QfCode")));
            
            if (string.IsNullOrEmpty(templateAppCode) || string.IsNullOrEmpty(upgradeAppCode))
            {
                PromptHelper.Prompt("请选择模板软件和待同步的软件！");
                this.Cursor = Cursors.Default;
                this.tsbGetDiff.Enabled = true;
                return;
            }

            this.tsbGetDiff.Enabled = false;
            this.tsbUpdate.Enabled = false;
            this.cmbTemplateAppName.Enabled = false;
            this.gridApp.Enabled = false;
            this.cmbQfNameExt.Enabled = false;
            this.cmbUpdateType.Enabled = false;
            this.cmbObjType.Enabled = false;
            this.txtObjName.Enabled = false;
            this.gridResult.Enabled = false;

            //创建进度计时器
            Timer processTimer = new Timer();
            processTimer.Enabled = true;
            processTimer.Interval = 1000;
            processTimer.Tick += new System.EventHandler(this.ProcessTimer_Tick);
            processTimer.Start();

            StartProcessDate = DateTime.Now;
            //this.lblStatus.Visible = true;

            bool successTag = false;
            string errorMessage = "";
            string masterBackupFileName = "";
            string configBackupFileName = "";
            DataSet dsDiff = new DataSet();

            Task task = Task.Run(() =>
            {
                dsDiff = GetAppConfigDBTableDiff(templateAppCode, upgradeAppCode, out successTag, out errorMessage);
            }).ContinueWith(t1 =>
            {
                processTimer.Stop();
                processTimer = null;
                this.tsbGetDiff.Enabled = true;
                this.tsbUpdate.Enabled = true;
                this.cmbTemplateAppName.Enabled = true;
                this.gridApp.Enabled = true;
                this.cmbQfNameExt.Enabled = true;
                this.cmbUpdateType.Enabled = true;
                this.cmbObjType.Enabled = true;
                this.txtObjName.Enabled = true;
                this.gridResult.Enabled = true;

                if (successTag && dsDiff.Tables.Count > 0)
                {
                    //添加选择框栏位
                    DataColumn dcIsSelected = new DataColumn("IsSelected", typeof(bool));
                    dcIsSelected.DefaultValue = false;
                    dsDiff.Tables[0].Columns.Add(dcIsSelected);
                    //添加扩展软件名称栏位
                    DataColumn dcQfNameExt = new DataColumn("QfNameExt", typeof(string));
                    dcQfNameExt.Expression = "QfName + '(' + QfCode + ')'";
                    dsDiff.Tables[0].Columns.Add(dcQfNameExt);
                    this.gridResult.DataSource = dsDiff.Tables[0];

                    //给搜索下拉框设置数据源
                    string[] updateTypeList = dsDiff.Tables[0].AsEnumerable().Select(t => t.Field<string>("UpdateType")).Distinct().ToArray();
                    string[] objTypeList = dsDiff.Tables[0].AsEnumerable().Select(t => t.Field<string>("ObjType")).Distinct().ToArray();
                    string[] qfCodeList = dsDiff.Tables[0].AsEnumerable().Select(t => t.Field<string>("QfNameExt")).Distinct().ToArray();
                    //var qfCodeList = dsDiff.Tables[0].AsEnumerable().Select(t => new { QfCode = t.Field<string>("QfCode"),QfNameExt = t.Field<string>("QfName") + "(" + t.Field<string>("QfCode") + ")" }).Distinct().ToArray();

                    //DataTable dtQfCode = new DataTable();
                    //dtQfCode.Columns.Add("QfCode", typeof(string));
                    //dtQfCode.Columns.Add("QfNameExt", typeof(string));

                    //for(int i = 0;i < qfCodeList.Length;i++)
                    //{
                    //    DataRow drQfCode = dtQfCode.NewRow();
                    //    drQfCode["QfCode"] = qfCodeList[i].QfCode;
                    //    drQfCode["QfNameExt"] = qfCodeList[i].QfNameExt;
                    //    dtQfCode.Rows.Add(drQfCode);
                    //}
                    //this.cmbQfNameExt.DataSource = qfCodeList;
                    //this.cmbQfNameExt.ValueMember = "QfCode";
                    //this.cmbQfNameExt.DisplayMember = "QfNameExt";
                    this.cmbQfNameExt.Items.AddRange(qfCodeList);
                    this.cmbUpdateType.Items.AddRange(updateTypeList);
                    this.cmbObjType.Items.AddRange(objTypeList);
                }
                else if (!successTag)
                {
                    PromptHelper.Prompt("获取数据库差异失败." + errorMessage);
                    this.Cursor = Cursors.Default;
                    this.tsbGetDiff.Enabled = true;
                    return;
                }
                this.Cursor = Cursors.Default;
                this.tsbGetDiff.Enabled = true;

            });

            /*
            //获取数据库差异
            QDDevPlat_V4 db = new QDDevPlat_V4();
            SqlParameter[] parameters = new SqlParameter[] {
                new SqlParameter("@templateAppCode",SqlDbType.VarChar,128),
                new SqlParameter("@upgradeAppCode",SqlDbType.VarChar,-1),
                new SqlParameter("@successTag",SqlDbType.Bit,1),
                new SqlParameter("@errorMessage",SqlDbType.VarChar,-1)
            };
            parameters[0].Value = templateAppCode;
            parameters[1].Value = upgradeAppCode;
            parameters[2].Direction = ParameterDirection.Output;
            parameters[3].Direction = ParameterDirection.Output;

            DataSet dsDiff = db.RunProcedure("Usp_Sys_GetAppConfigDBTableDiff", parameters);
            bool successTag = false;
            string errorMessage = "";

            if (parameters != null && parameters.Length >= 4)
            {
                if (parameters[2].Value != null && !string.IsNullOrEmpty(parameters[2].Value.ToString()))
                {
                    successTag = bool.Parse(parameters[2].Value.ToString());
                }
                errorMessage = string.Concat(parameters[3].Value);
            }

            if (successTag && dsDiff.Tables.Count > 0)
            {
                //添加选择框栏位
                DataColumn dcIsSelected = new DataColumn("IsSelected", typeof(bool));
                dcIsSelected.DefaultValue = false;
                dsDiff.Tables[0].Columns.Add(dcIsSelected);
                //添加扩展软件名称栏位
                DataColumn dcQfNameExt = new DataColumn("QfNameExt", typeof(string));
                dcQfNameExt.Expression = "QfName + '(' + QfCode + ')'";
                dsDiff.Tables[0].Columns.Add(dcQfNameExt);
                this.gridResult.DataSource = dsDiff.Tables[0];

                //给搜索下拉框设置数据源
                string[] updateTypeList = dsDiff.Tables[0].AsEnumerable().Select(t => t.Field<string>("UpdateType")).Distinct().ToArray();
                string[] objTypeList = dsDiff.Tables[0].AsEnumerable().Select(t => t.Field<string>("ObjType")).Distinct().ToArray();
                string[] qfCodeList = dsDiff.Tables[0].AsEnumerable().Select(t => t.Field<string>("QfNameExt")).Distinct().ToArray();
                //var qfCodeList = dsDiff.Tables[0].AsEnumerable().Select(t => new { QfCode = t.Field<string>("QfCode"),QfNameExt = t.Field<string>("QfName") + "(" + t.Field<string>("QfCode") + ")" }).Distinct().ToArray();

                //DataTable dtQfCode = new DataTable();
                //dtQfCode.Columns.Add("QfCode", typeof(string));
                //dtQfCode.Columns.Add("QfNameExt", typeof(string));

                //for(int i = 0;i < qfCodeList.Length;i++)
                //{
                //    DataRow drQfCode = dtQfCode.NewRow();
                //    drQfCode["QfCode"] = qfCodeList[i].QfCode;
                //    drQfCode["QfNameExt"] = qfCodeList[i].QfNameExt;
                //    dtQfCode.Rows.Add(drQfCode);
                //}
                //this.cmbQfNameExt.DataSource = qfCodeList;
                //this.cmbQfNameExt.ValueMember = "QfCode";
                //this.cmbQfNameExt.DisplayMember = "QfNameExt";
                this.cmbQfNameExt.Items.AddRange(qfCodeList);
                this.cmbUpdateType.Items.AddRange(updateTypeList);
                this.cmbObjType.Items.AddRange(objTypeList);
            }
            else if (!successTag)
            {
                PromptHelper.Prompt("获取数据库差异失败." + errorMessage);
                this.Cursor = Cursors.Default;
                this.tsbGetDiff.Enabled = true;
                return;
            }
            this.Cursor = Cursors.Default;
            this.tsbGetDiff.Enabled = true;
            */
        }
                
        /// <summary>
        /// 获取数据库差异
        /// </summary>
        /// <param name="templateAppCode"></param>
        /// <param name="upgradeAppCode"></param>
        /// <param name="successTag"></param>
        /// <param name="errorMessage"></param>
        private DataSet GetAppConfigDBTableDiff(string templateAppCode,string upgradeAppCode,out bool successTag,out string errorMessage)
        {
            successTag = false;
            errorMessage = "";

            //获取数据库差异
            QDDevPlat_V4 db = new QDDevPlat_V4();
            SqlParameter[] parameters = new SqlParameter[] {
                new SqlParameter("@templateAppCode",SqlDbType.VarChar,128),
                new SqlParameter("@upgradeAppCode",SqlDbType.VarChar,-1),
                new SqlParameter("@successTag",SqlDbType.Bit,1),
                new SqlParameter("@errorMessage",SqlDbType.VarChar,-1)
            };
            parameters[0].Value = templateAppCode;
            parameters[1].Value = upgradeAppCode;
            parameters[2].Direction = ParameterDirection.Output;
            parameters[3].Direction = ParameterDirection.Output;

            DataSet dsDiff = db.RunProcedure("Usp_Sys_GetAppConfigDBTableDiff", parameters);            

            if (parameters != null && parameters.Length >= 4)
            {
                if (parameters[2].Value != null && !string.IsNullOrEmpty(parameters[2].Value.ToString()))
                {
                    successTag = bool.Parse(parameters[2].Value.ToString());
                }
                errorMessage = string.Concat(parameters[3].Value);
            }

            return dsDiff;
        }

        /// <summary>
        /// 更新运行时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProcessTimer_Tick(object sender, EventArgs e)
        {
            int totalProcessSeconds = Convert.ToInt32(new TimeSpan(DateTime.Now.Ticks).Subtract(new TimeSpan(StartProcessDate.Ticks)).TotalSeconds);
            //转换成相应的大单位            
            int processDays = 0;
            int processHours = 0;
            int processMinutes = 0;
            int processSeconds = 0;

            processDays = Convert.ToInt32(totalProcessSeconds / (24 * 60 * 60));
            processHours = Convert.ToInt32((totalProcessSeconds - processDays * (24 * 60 * 60)) / (60 * 60));
            processMinutes = Convert.ToInt32((totalProcessSeconds - processDays * (24 * 60 * 60) - processHours * (60 * 60)) / (60));
            processSeconds = Convert.ToInt32((totalProcessSeconds - processDays * (24 * 60 * 60) - processHours * (60 * 60) - processMinutes * (60)) / (1));

            string processTimeDesc = "";
            if (processDays > 0)
            {
                processTimeDesc = processDays.ToString() + "天" + processHours.ToString() + "时" + processMinutes.ToString() + "分" + processSeconds.ToString() + "秒";
            }
            else if (processDays == 0 && processHours > 0)
            {
                processTimeDesc = processHours.ToString() + "时" + processMinutes.ToString() + "分" + processSeconds.ToString() + "秒";
            }
            else if (processDays == 0 && processHours == 0 && processMinutes > 0)
            {
                processTimeDesc = processMinutes.ToString() + "分" + processSeconds.ToString() + "秒";
            }
            else
            {
                processTimeDesc = processSeconds.ToString() + "秒";
            }

            this.toolStripStatusLabel1.Text = "已运行" + processTimeDesc;
        }

        //升级
        private void tsbUpdate_Click(object sender, EventArgs e)
        {
            this.gridResult.EndEdit();
            //this.Cursor = Cursors.WaitCursor;
            //this.tsbUpdate.Enabled = false;
            //检查参数
            if (this.gridResult.DataSource == null)
            {
                return;
            }
            DataTable dtResult = (DataTable)this.gridResult.DataSource;
            dtResult.AcceptChanges();
            //注意要过滤
            DataTable dtResultDisplay = dtResult.Clone();
            DataRow[] drsResult = dtResult.Select(dtResult.DefaultView.RowFilter);
            drsResult.ToList<DataRow>().ForEach((r) => dtResultDisplay.ImportRow(r));

            string updateCommand = string.Join(";"+System.Environment.NewLine, dtResultDisplay.AsEnumerable().Where(t => t.Field<bool>("IsSelected")).Select(t => t.Field<string>("UpdateCommand")));

            if (string.IsNullOrEmpty(updateCommand))
            {
                PromptHelper.Prompt("请选择待执行的语句！");
                //this.Cursor = Cursors.Default;
                //this.tsbUpdate.Enabled = true;
                return;
            }
            //改成将SQL语句粘贴到QD.DbManager.QDSEditor
            Form frm = Application.OpenForms["QDSEditor"];
            if (frm == null)
            {
                string templateAppCode = string.Concat(this.cmbTemplateAppName.SelectedValue);
                DataTable dtTemplate = this.cmbTemplateAppName.DataSource as DataTable;
                string configDatabase = dtTemplate.AsEnumerable().Where(t => t.Field<string>("QfCode") == templateAppCode).Select(t => t.Field<string>("ConfigDataBase")).FirstOrDefault();
                if (string.IsNullOrEmpty(configDatabase))
                {
                    configDatabase = "QDDevPlat_V4";
                }
                DbConfig.Instance.DbConfigName = configDatabase;

                frm = new QD.DbManager.QDSEditor(DbConfig.Instance);
                ((QD.DbManager.QDSEditor)frm).AddNewTextEditor(updateCommand, "升级配置库");
                frm.Show();
            }
            else
            {
                frm.Activate();
            }

            //QDDevPlat_V4 db = new QDDevPlat_V4();
            //try
            //{
            //    db.ExecuteNonQuery(updateCommand);
            //    PromptHelper.Prompt("升级成功！");
            //}
            //catch(Exception ex)
            //{
            //    PromptHelper.Prompt("升级失败！");
            //}
            //this.Cursor = Cursors.Default;
            //this.tsbUpdate.Enabled = true;
        }

        private void cmsApp_SelectAll_Click(object sender, EventArgs e)
        {
            //结束列表的编辑状态,否则可能无法改变CheckBox的状态
            gridApp.EndEdit();
            for (var i = 0; i < gridApp.Rows.Count; i++)
            {
                gridApp.Rows[i].Cells["gridApp_IsSelected"].Value = true;//设置为选中状态
            }
        }

        private void cmsApp_UnselectAll_Click(object sender, EventArgs e)
        {
            //结束列表的编辑状态,否则可能无法改变CheckBox的状态
            gridApp.EndEdit();
            for (var i = 0; i < gridApp.Rows.Count; i++)
            {
                gridApp.Rows[i].Cells["gridApp_IsSelected"].Value = false;//设置为不选中状态
            }
        }

        private void cmsApp_InvertSelect_Click(object sender, EventArgs e)
        {
            //结束列表的编辑状态,否则可能无法改变CheckBox的状态
            gridApp.EndEdit();
            for (var i = 0; i < gridApp.Rows.Count; i++)
            {
                if ((bool)gridApp.Rows[i].Cells["gridApp_IsSelected"].Value == true)
                {
                    gridApp.Rows[i].Cells["gridApp_IsSelected"].Value = false;//设置为不选中状态
                }
                else
                {
                    gridApp.Rows[i].Cells["gridApp_IsSelected"].Value = true;//设置为选中状态
                }
            }
        }

        private void cmsResult_SelectAll_Click(object sender, EventArgs e)
        {
            //结束列表的编辑状态,否则可能无法改变CheckBox的状态
            gridResult.EndEdit();
            for (var i = 0; i < gridResult.Rows.Count; i++)
            {
                gridResult.Rows[i].Cells["gridResult_IsSelected"].Value = true;//设置为选中状态
            }
        }

        private void cmsResult_UnselectAll_Click(object sender, EventArgs e)
        {
            //结束列表的编辑状态,否则可能无法改变CheckBox的状态
            gridResult.EndEdit();
            for (var i = 0; i < gridResult.Rows.Count; i++)
            {
                gridResult.Rows[i].Cells["gridResult_IsSelected"].Value = false;//设置为不选中状态
            }
        }

        private void cmsResult_InvertSelect_Click(object sender, EventArgs e)
        {
            //结束列表的编辑状态,否则可能无法改变CheckBox的状态
            gridResult.EndEdit();
            for (var i = 0; i < gridResult.Rows.Count; i++)
            {
                if ((bool)gridResult.Rows[i].Cells["gridResult_IsSelected"].Value == true)
                {
                    gridResult.Rows[i].Cells["gridResult_IsSelected"].Value = false;//设置为不选中状态
                }
                else
                {
                    gridResult.Rows[i].Cells["gridResult_IsSelected"].Value = true;//设置为选中状态
                }
            }
        }

        /// <summary>
        /// 搜索结果
        /// </summary>
        private void searchResult()
        {
            string qfNameExt = string.Concat(this.cmbQfNameExt.Text);//软件代号
            string updateType = string.Concat(this.cmbUpdateType.Text);//更新类型
            string objType = string.Concat(this.cmbObjType.Text);//对象类型
            string objName = this.txtObjName.Text;//对象名称
            
            List<string> searchConditionList = new List<string>();
            if (!string.IsNullOrEmpty(qfNameExt))
            {                
                searchConditionList.Add("QfNameExt in ('" + string.Join("','", qfNameExt.Split(new char[] { ',' }).Select(t => t.Trim()).ToArray()) + "')");
            }
            if (!string.IsNullOrEmpty(updateType))
            {
                searchConditionList.Add("UpdateType in ('" + string.Join("','", updateType.Split(new char[] { ',' }).Select(t => t.Trim()).ToArray()) + "')");
            }
            if (!string.IsNullOrEmpty(objType))
            {
                searchConditionList.Add("ObjType in ('" + string.Join("','", objType.Split(new char[] { ',' }).Select(t => t.Trim()).ToArray()) + "')");
            }
            if (!string.IsNullOrEmpty(objName))
            {
                searchConditionList.Add("ObjName like '%" + objName.Trim() + "%'");
            }
            string searchCondition = string.Join(" and ", searchConditionList);

            ((DataTable)this.gridResult.DataSource).DefaultView.RowFilter = searchCondition;
        }

        private void cmbUpdateType_TextChanged(object sender, EventArgs e)
        {
            searchResult();//搜索结果
        }

        private void cmbQfNameExt_TextChanged(object sender, EventArgs e)
        {
            searchResult();//搜索结果
        }

        private void cmbObjType_TextChanged(object sender, EventArgs e)
        {
            searchResult();//搜索结果
        }

        private void txtObjName_Leave(object sender, EventArgs e)
        {
            searchResult();//搜索结果
        }

        private void txtObjName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                searchResult();//搜索结果
            }
        }
    }
}
